//
//  GZSegmentBar.m
//  GZSegmentBar_Example
//
//  Created by Guo Rui on 2018/1/10.
//  Copyright © 2018年 GR. All rights reserved.
//

#import "GZSegmentBar.h"
#import <GRFMBaseLib/UIView+XMGLayout.h>

static CGFloat const kMinMargin = 30.f;
static NSInteger const kTagBaseValue = 100;
static CGFloat const kScrollX = 7.f;

@interface GZSegmentBar()
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) NSMutableArray <UIButton *> *btnArray;
@property (strong, nonatomic) UIView *indicatorView;

@property (strong, nonatomic) UIButton *selectedBtn;
@end

@implementation GZSegmentBar

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.scrollView.backgroundColor = [UIColor whiteColor];
        self.indicatorView.backgroundColor = [UIColor redColor];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.scrollView.frame = CGRectMake(kScrollX, 0, self.width - 2 * kScrollX, self.height);
    
    // 1. btn布局
    // 1.1 计算margin
    CGFloat totalWidth = 0;
    for (UIButton *btn in self.btnArray) {
        [btn sizeToFit];
        totalWidth += btn.width;
    }
    
    CGFloat margin = (self.scrollView.width - totalWidth) / (self.btnArray.count - 1);
    if (margin < kMinMargin) {
        margin = kMinMargin;
    }
    
    // 1.2 btn布局
    CGFloat lastX = 0;
    for (UIButton *btn in self.btnArray) {
        btn.x = lastX;
        btn.y = (self.height - btn.height) / 2.f;
        lastX += (btn.width + margin);
    }
    
    // 2. scrollView
    self.scrollView.contentSize = CGSizeMake(lastX - margin, self.height);
    
    // 3. indicator
    self.indicatorView.height = 2.f;
    self.indicatorView.y = self.height - self.indicatorView.height;
}

#pragma mark - Public
- (void)setSegmentItems:(NSArray<id<GZSegmentBarModelProtocol>> *)items
{
    [self.btnArray makeObjectsPerformSelector:@selector(removeAllObjects)];
    [self.btnArray removeAllObjects];
    
    NSInteger index = 0;
    for (id<GZSegmentBarModelProtocol> item in items) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:item.content forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        btn.tag = (kTagBaseValue + index++);
        [btn addTarget:self action:@selector(segmentButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:btn];
        
        [self.btnArray addObject:btn];
    }
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    [self setupSelectedButtonWithIndex:0];
    [self setupIndicatorViewWithIndex:0];
}

- (void)setSelectIndex:(NSInteger)selectIndex
{
    if (self.btnArray.count == 0 || selectIndex < 0 || selectIndex > self.btnArray.count - 1) {
        return;
    }
    
    _selectIndex = selectIndex;
    
    UIButton *btn = [self.btnArray objectAtIndex:selectIndex];
    [self segmentButtonDidClick:btn];
}

#pragma mark - Private
- (void)setupIndicatorViewWithIndex:(NSInteger)index
{
    UIButton *clickBtn = [self.btnArray objectAtIndex:index];
    
    [UIView animateWithDuration:.2 animations:^{
        self.indicatorView.x = clickBtn.x;
        self.indicatorView.width = clickBtn.width;
    }];
}

- (void)setupSelectedButtonWithIndex:(NSInteger)index
{
    UIButton *btn = [self.btnArray objectAtIndex:index];
    
    self.selectedBtn.selected = NO;
    btn.selected = YES;
    self.selectedBtn = btn;
    
    _selectIndex = index;
}

- (void)scrollToPointWithButton:(UIButton *)btn
{
    if (self.scrollView.width <= kScrollX * 2) {
        return;
    }
    
    CGFloat scrollX = btn.centerX - self.scrollView.width * 0.5;
    
    if (scrollX < 0) {
        scrollX = 0;
    }
    if (scrollX > self.scrollView.contentSize.width - self.scrollView.width) {
        scrollX = self.scrollView.contentSize.width - self.scrollView.width;
    }
    
    [self.scrollView setContentOffset:CGPointMake(scrollX, 0) animated:YES];
}

#pragma mark - Actions
- (void)segmentButtonDidClick:(UIButton *)btn
{
    NSInteger index = btn.tag - kTagBaseValue;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(segmentBar:fromIndex:toIndex:)]) {
        [self.delegate segmentBar:self fromIndex:self.selectedBtn.tag - kTagBaseValue toIndex:index];
    }
    
    // 设置选择按钮的状态
    [self setupSelectedButtonWithIndex:index];
    
    // 设置点击处，滚动到中心
    [self scrollToPointWithButton:btn];
    
    
    // 设置指示器的位置
    [self setupIndicatorViewWithIndex:index];
}

#pragma mark - Getter
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_scrollView];
    }
    return _scrollView;
}

- (UIView *)indicatorView
{
    if (!_indicatorView) {
        _indicatorView = [[UIView alloc] init];
        [self.scrollView addSubview:_indicatorView];
    }
    return _indicatorView;
}

- (NSMutableArray *)btnArray
{
    if (!_btnArray) {
        _btnArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _btnArray;
}

@end
